package be.djdb.custom;

import java.io.InputStream;
import java.util.LinkedHashMap;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;

public class WorkspaceFolders {
	private LinkedHashMap <String, IPath>workspacepaths;
	private IPath projectPath;
	private IProject project;
    private IProgressMonitor monitor;
    private IWorkspaceRoot root;
    /**
	 * 
	 * <pre>
	    protected void createProject(IProgressMonitor monitor){
	      monitor.beginTask(Resources.getString("eclipse.creatingproject"),50);
	      try{
	         IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	         monitor.subTask(Resources.getString("eclipse.creatingdirectories"));
	         IProject project = root.getProject(namePage.getProjectName());
	 	  }
	   </pre>
	 * */
	public WorkspaceFolders(IProject project,IProgressMonitor monitor) {
		this.root = ResourcesPlugin.getWorkspace().getRoot();
		this.project = project;
		this.monitor = monitor;
		getprojectpath();
	}
	private void getprojectpath(){
		projectPath = project.getFullPath(); 
	}
	public void CreatIfNotexist(String[] dirs) throws CoreException{
		for (int i = 0; i < dirs.length; i++){
			IFolder tempFolder = root.getFolder(projectPath.append(dirs[i]));
			createFolder(tempFolder, monitor);
		}
	}
	private void createFolder(IFolder folder,IProgressMonitor monitor) throws CoreException{
		if (!folder.exists()){
		   IContainer ct = folder.getParent();
		   IFolder parent =(ct instanceof IFolder)? (IFolder)ct:null;
		   if(parent !=null && !(parent).exists())
		        createFolder((IFolder)parent,monitor);//wil make recursief all uperdirs
		        folder.create(false,true,monitor);
		}
	}
	/**
	 *
	 Class clasz = getClass();
     InputStream indexIS = clasz.getResourceAsStream("/org/ananas/xm/eclipse/resources/index.xml"),
	 * @throws CoreException 
	*/
	private void createFile(String path,String name ,InputStream in) throws CoreException{
		IPath apath = workspacepaths.get(path);
		if (!root.getFolder(apath).exists()){
			createFolder(root.getFolder(apath),monitor);
		}
		IPath afilePath = apath.append(name);
		IFile afile  =  root.getFile(afilePath);
		afile.create(in,false,new SubProgressMonitor(monitor,10));
	}
}
